import { getCurrentTimeParam } from "./globalTimeFilter.js";
import { API_CONFIG } from "./config.js";

document.addEventListener("DOMContentLoaded", function () {
  // 获取事发区域统计容器
  const cjliangElement = document.getElementById("cjliang");
  const footChild = document.querySelector(".footparent3 .footChild");
  if (!cjliangElement || !footChild) return;

  const newHTML = `
        <div class="incident-area-container">
            <div id="incident-area-chart" style=" width: 100%; height: 100%;"></div>
        </div>
    `;

  // 插入到容器中
  cjliangElement.innerHTML = newHTML;

  // 添加样式
  const style = document.createElement("style");
  style.innerHTML = `
        .incident-area-container {
            height: 100%;
            width: 100%;
            border-radius: 8px;
            padding: 15px;
            border: 1px solid rgba(36, 187, 236, 0.2);
            display: flex;
            flex-direction: column;
            margin-top: 100px;
        }
        
        .statistics-rules {
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
            border: 1px solid rgba(36, 187, 236, 0.15);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
        }
        
        .rule-title {
            font-weight: bold;
            color: #24bbec;
            font-size: 1.1rem;
            margin-bottom: 10px;
            text-align: center;
            border-bottom: 1px solid rgba(36, 187, 236, 0.3);
            padding-bottom: 8px;
        }
        
        .rule-content {
            color: #e6f7ff;
            line-height: 1.6;
            font-size: 0.95rem;
            text-align: center;
        }
        
        #incident-area-chart {
            flex: 1;
            width: 100%;
        }
    `;
  document.head.appendChild(style);

  // 初始化图表
  initIncidentAreaChart();
});

function initIncidentAreaChart() {
  const chartDom = document.getElementById("incident-area-chart");
  const chart = echarts.init(chartDom);

  let sortedBureaus = [];
  let sortedData = [];
  let startIndex = 0;
  const visibleItems = 8;

  // 监听时间变化事件
  document.addEventListener("timePeriodChanged", function (event) {
    fetchDataAndUpdate();
  });

  function fetchDataAndUpdate() {
    let timeParam = getCurrentTimeParam();


    const id = "sdhwreytwetqewvttwetgvefgdsgerg";
    const type = "1";

    // 使用普通对象而不是URLSearchParams
    const params = {
      id: id,
      time: timeParam,
      type: type,
    };

    // 修正URL路径 - 添加/api
    const url = `${API_CONFIG.BASE_URL}/api/metrics/${id}/single-metrics-value`;

    console.log("发送请求到:", url, "参数:", params); // 调试用

    axios
      .get(url, { params })
      .then((response) => {
        if (response.data && response.data.code === "00000") {
          const result = response.data.data;
          // 处理数据，提取区域和工单数量
          console.log("获取到的事发区域数据:", result); // 调试用
          const bureaus = [];
          const data = [];

          result.forEach((item) => {
            // 使用calculate_time作为区域标识（因为area字段为空）
            bureaus.push(item.calculate_time);
            data.push(parseInt(item.area_work_order_count));
          });
          updateChart(bureaus, data);
        } else {
          console.error(
            "获取事发区域数据失败:",
            response.data ? response.data.msg : "未知错误"
          );
        }
      })
      .catch((error) => {
        console.error("获取事发区域数据失败:", error);
      });
  }
  function updateChart(bureaus, data) {
    // 按工单数量排序 (从多到少)
    const sortedIdxs = data
      .map((val, idx) => ({ val, idx }))
      .sort((a, b) => b.val - a.val)
      .map((item) => item.idx);

    sortedBureaus = sortedIdxs.map((idx) => bureaus[idx]);
    sortedData = sortedIdxs.map((idx) => data[idx]);

    // 图表配置
    const option = {
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "shadow",
        },
        formatter: function (params) {
          const data = params[0];
          return `${data.name}: ${data.value || 0} 次`;
        },
        backgroundColor: "rgba(6, 33, 68, 0.9)",
        borderColor: "#24bbec",
        textStyle: {
          color: "#fff",
        },
      },
      grid: {
        left: "5%",
        right: "5%",
        bottom: "10%",
        top: "5%",
        containLabel: true,
      },
      xAxis: {
        type: "value",
        name: "工单数量",
        nameLocation: "end",
        nameTextStyle: {
          color: "#a2d3e8",
        },
        axisLine: {
          lineStyle: {
            color: "rgba(162, 211, 232, 0.5)",
          },
        },
        axisLabel: {
          color: "#a2d3e8",
          fontSize: 20,
        },
        splitLine: {
          lineStyle: {
            color: "rgba(162, 211, 232, 0.1)",
          },
        },
      },
      yAxis: {
        type: "category",
        data: sortedBureaus,
        axisLine: {
          lineStyle: {
            color: "rgba(162, 211, 232, 0.5)",
          },
        },
        axisLabel: {
          color: "#e6f7ff",
          fontSize: 20,
        },
      },
      series: [
        {
          name: "工单数量",
          type: "bar",
          data: sortedData,
          label: {
            show: true,
            position: "right",
            formatter: "{c}",
            color: "#fff",
            fontSize: 20,
          },
          itemStyle: {
            color: function (params) {
              // 根据排名设置不同的颜色
              const rank = params.dataIndex;
              if (rank < 3) {
                return ["#24d39a", "#24bbec", "#ffc640"][rank];
              } else {
                const colorStops = [
                  { offset: 0, color: "#1d6fa0" },
                  { offset: 1, color: "#1976D2" },
                ];
                return {
                  type: "linear",
                  x: 0,
                  y: 0,
                  x2: 1,
                  y2: 0,
                  colorStops: colorStops,
                };
              }
            },
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowColor: "rgba(36, 187, 236, 0.5)",
            },
          },
        },
      ],
      animation: true,
      animationDuration: 1000,
      animationEasing: "cubicInOut",
    };

    chart.setOption(option);
  }

  // 初始加载
  fetchDataAndUpdate();

  // 每10秒更新一次数据
  setInterval(fetchDataAndUpdate, 1000000);

  function scrollChart() {
    if (sortedBureaus.length <= visibleItems) return;

    startIndex = (startIndex + 1) % (sortedBureaus.length - visibleItems + 1);

    chart.setOption({
      yAxis: {
        data: sortedBureaus.slice(startIndex, startIndex + visibleItems),
      },
      series: [
        {
          data: sortedData.slice(startIndex, startIndex + visibleItems),
        },
      ],
    });
  }

  // 每5秒滚动一次
  let scrollInterval = setInterval(scrollChart, 5000);

  // 处理窗口大小变化
  window.addEventListener("resize", function () {
    chart.resize();
  });

  // 鼠标悬停时暂停滚动
  chartDom.addEventListener("mouseover", () => {
    clearInterval(scrollInterval);
  });

  chartDom.addEventListener("mouseout", () => {
    scrollInterval = setInterval(scrollChart, 5000);
  });
}
